<template>
  <el-dialog v-if="dialogFormVisible" v-el-drag-dialog custom-class="wfNodeLoglist-dialog" :fullscreen="fullscreen" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :width="winWidth+'px'" :title="title" @close="closeDialog">
    <div v-if="loading" v-loading="loading" class="el-dialog__body" />
    <template slot="title">
      <div style="width:100%">
        <span class="el-dialog__title">{{ title }}</span>
        <span style="float:right;cursor: pointer;margin-right:35px;margin-top:6px" @click="setFullScreen">
          <!-- <i v-show="!fullscreen" class="el-icon-full-screen" /><i v-show="fullscreen" class="el-icon-aim" /> -->
          <span v-show="!fullscreen">
            <svg-icon icon-class="wflow-fullscreen" style="color:#909599;font-size:16px;" />
          </span>
          <span v-show="fullscreen">
            <svg-icon icon-class="wflow-outfullscreen" style="color:#909599;font-size:16px;" />
          </span>
        </span>
      </div>
    </template>
    <el-tabs v-model="activeName">
      <el-tab-pane label="办文跟踪" name="todoLog" class="flow-node-logs">
        <el-scrollbar :native="false" tag="div">
          <el-table v-if="!loading" :data="todoLogList" height="100%" class="wfNodelog-container" border style="width: 100%" :row-class-name="rowClassName">
            <el-table-column label="处理环节" prop="nodeName" width="120" align="left" />
            <el-table-column label="处理人" prop="staffName" width="80" align="center" />
            <el-table-column label="开始时间" class-name="col-time" label-class-name="col-time" prop="createTime" width="90" align="center" />
            <el-table-column v-if="showOpenTime==1" class-name="col-time" label-class-name="col-time" label="打开时间" prop="openTime" width="90" align="center" />
            <el-table-column label="完成时间" class-name="col-time" label-class-name="col-time" prop="completeTime" width="90" align="center" />
            <el-table-column label="办理时限" class-name="col-time" label-class-name="col-time" prop="limitTime" width="90" align="center" />
            <el-table-column label="办理时长" prop="processedTimeLength" width="90" align="center" />
            <el-table-column label="超时时长" prop="timeoutTimeLength" width="90" align="center" />
            <el-table-column label="处理意见" class-name="col-idea" label-class-name="col-idea" prop="idea" align="center">
              <template slot-scope="scope">
                <span v-html="textDispose(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="提交路径" class-name="col-path" label-class-name="col-path" prop="pathName" width="150" align="left">
              <template slot-scope="scope">
                <span :style="{'color':scope.row.pathName.indexOf('退回') > -1?'red':''}" v-html="scope.row.pathName" />
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </el-tab-pane>
      <el-tab-pane label="阅文日志" name="toreadLog" class="read-node-logs">
        <el-scrollbar :native="false" tag="div">
          <el-table v-if="!loading" :data="toreadLogList" height="100%" border style="width: 100%">
            <el-table-column label="处理环节" prop="nodeName" width="150" align="left" />
            <el-table-column label="处理人" prop="staffName" width="100" align="center" />
            <el-table-column label="开始时间" class-name="col-time" label-class-name="col-time" prop="createTime" width="150" align="center" />
            <el-table-column label="阅文时间" class-name="col-time" label-class-name="col-time" prop="completeTime" width="150" align="center" />
            <el-table-column label="备注">
              <template slot-scope="scope">
                <span v-html="scope.row.pathName||scope.row.idea" />
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>

      </el-tab-pane>
      <el-tab-pane v-if="showWflowTrace" label="流程跟踪图" name="technological" class="technological-WflowTrace">
        <el-scrollbar :native="false" tag="div" class="WflowTrace-scrollbar">
          <WflowTrace v-if="activeName === 'technological'" :table-list="WflowTraceList" :wf-instance="wfInstance" @clickloading="clickloading" />
        </el-scrollbar>
      </el-tab-pane>
      <el-tab-pane label="完成情况分析" name="completeLog">
        <el-scrollbar :native="false" tag="div">
          <div style="width:100%;height:300px">
            <echart-columnar
              v-if="echarts"
              :top="'50'"
              :x-chart-num="3"
              :color="colors"
              :x-data="xdata"
              :y-data="ydata"
              :x-type-name="xTypeName"
              :chart-type="chartType"
              :is-legend="true"
              :legend-align="{location:'top,right',align:'0'}"
              :show-data="{ isdata: true, align: 'top', color: '#000' }"
              :bar-category-gap="'0'"
              :is-stack="true"
              :x-label-rotate="xLabelRotate"
              :label-formatter="labelFormatter"
              :x-label-formatter="xLabelFormatter"
              :echarts-click="echartsClick"
              :y-unit="{minInterval:1}"
            />
          </div>
          <el-table :data="tableList" border style="width: 100%;margin-top:20px">
            <el-table-column label="处理环节" prop="nodeName" width="120" align="left" />
            <el-table-column label="处理人" prop="staffName" width="80" align="center" />
            <el-table-column label="开始时间" prop="createTime" width="85" align="center" />
            <el-table-column label="完成时间" prop="completeTime" width="85" align="center" />
            <el-table-column label="办理时限" width="85" align="center" prop="limitTime" />
            <el-table-column label="办理时长" width="85" align="center" prop="processedTimeLength" />
            <el-table-column label="超时时长" width="90" prop="timeoutTimeLength" align="center" />
            <el-table-column label="处理意见" prop="idea" width="150" align="center">
              <template slot-scope="scope">
                <span v-html="textDispose(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="提交路径" prop="pathName" align="center">
              <template slot-scope="scope">
                <span :style="{'color':scope.row.pathName.indexOf('退回') > -1?'red':''}" v-html="scope.row.pathName" />
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script>
import { parseTime } from '@/global/utils/index'
import qs from 'qs'

export default {
    name: 'WfNodelogList',
    components: {
    },
    props: {
        showOpenTime: { type: Number, default: 0 },
        winWidth: { type: Number, default: 1000 }
    },
    data() {
        return {
            title: '流程跟踪',
            tableList: [],
            showWflowTrace: true, // 是否显示图形化流程跟踪，udm流程不显示
            showtechnological: false,
            colors: ['#67C23A', '#409EFF', '#F56C6C'],
            xdata: [],
            ydata: [[]],
            echarts: false,
            ids: [],
            xTypeName: [{ name: '已办' }, { name: '未办（未超时）' }, { name: '未办（已超时）' }],
            chartType: [
                { type: 'bar', yAxisIndex: 0 },
                { type: 'bar', yAxisIndex: 0 },
                { type: 'bar', yAxisIndex: 0 }
            ],
            allLabelNum: [],
            dialogFormVisible: false,
            activeName: 'todoLog',
            wfInstance: {},
            todoLogList: [],
            toreadLogList: [],
            loading: false,
            fullscreen: false,
            WflowTraceList: [],
            xLabelRotate: 0
        }
    },
    computed: {

    },
    watch: {
        activeName(val) {
            this.echarts = false
            if (val === 'completeLog') {
                this.getXdata()
                this.echarts = true
            } else if (val === 'infoRecord') {
                this.getInfoRecordData()
            } else if (val === 'todoLog') {
                // this.$refs.multipleTable.clearSelection()
            } else if (val === 'technological') {
                this.$nextTick(() => {
                    this.showtechnological = true
                })
            }
        },
        immediate: true
    },
    created() {
        this.$options.components['echartColumnar'] = this.$loadComponent('@/wapp/common/components/Echarts/src/EchartColumnar')

        this.$bus.on('showWfNodelogList', this.showWfNodelogList)
        this.$bus.on('btnAddReader', this.btnAddReaderClick)
        this.$bus.on('btnReadedClick', this.btnReadedClick)
    },
    beforeDestroy() {
        this.$bus.off('showWfNodelogList', this.showWfNodelogList)
        this.$bus.off('btnAddReader', this.btnAddReaderClick)
        this.$bus.off('btnReadedClick', this.btnReadedClick)
    },
    mounted() {
    },
    methods: {
        showWfNodelogList(wfInstance) {
            const _this = this
            if (_this.loading) {
                return
            }
            _this.loading = true

            this.dialogFormVisible = true
            this.wfInstance = wfInstance
            if (wfInstance.udmNodes) {
                this.showWflowTrace = false
            }

            this.$http({
                method: 'POST',
                contentType: 'application/x-www-form-urlencoded',
                params: { 'wfInstanceId': wfInstance.id },
                url: 'workflow/wfInstanceNodelog/listWfNodelog'
            }).then(res => {
                if (res.code === 'success') {
                    res.body.listdata.forEach(function(wflog) {
                        if (wflog.taskType > 0 && wflog.taskType < 9) {
                            _this.setTimeLength(wflog)
                            if (wflog.openTime === null) {
                                wflog.openTime = '未打开'
                            }
                            if (wflog.completeTime === null) {
                                wflog.completeTime = '未完成'
                            }
                            if (wflog.limitTime === null) {
                                wflog.limitTime = '无时限'
                            }
                            if (wflog.idea === null || wflog.idea === '') wflog.idea = '无'
                            if (wflog.pathName === null) wflog.pathName = '未提交'
                            if (wflog.status === 7) {
                                wflog.completeTime = '未完成'
                                wflog.pathName = '<span style="color:#ff0000">未提交，被撤回</span>'
                            }

                            _this.todoLogList.push(wflog)
                        } else {
                            if (wflog.status === 7) {
                                wflog.pathName = '<span style="color:#ff0000">未提交，被撤回</span>'
                                wflog.completeTime = '未读'
                            } else if (wflog.completeTime === null) {
                                wflog.completeTime = '未读'
                            }

                            _this.toreadLogList.push(wflog)
                        }
                        _this.WflowTraceList.push(wflog)
                    })

                    _this.loading = false
                } else {
                    this.$alert(res.message, '操作提示', { type: 'error', callback: () => {
                        _this.dialogFormVisible = false
                        this.fullscreen = false
                        _this.loading = false
                    } })
                }
            }).catch(err => {
                console.log(err)
                _this.loading = false
            })
        },
        setTimeLength(wflog) {
            const startTime = parseTime(wflog.createTime)
            let endTime = new Date()
            if (wflog.completeTime !== null) {
                endTime = parseTime(wflog.completeTime)
            }
            if (endTime.getTime() < startTime.getTime()) {
                endTime = startTime
            }
            // 开始时间到完成时间的分钟数
            const timeLength = (endTime.getTime() - startTime.getTime()) / (1000 * 60)

            const d = timeLength / (24 * 60)
            const h = (timeLength % (24 * 60)) / 60
            const m = (timeLength % (24 * 60)) % 60
            const s = ((endTime.getTime() - startTime.getTime()) / 1000) % 60

            if (d >= 1) {
                wflog.processedTimeLength = parseInt(d) + '天' + parseInt(h) + '时' + parseInt(m) + '分'
            } else if (h >= 1) {
                wflog.processedTimeLength = parseInt(h) + '时' + parseInt(m) + '分'
            } else {
                wflog.processedTimeLength = parseInt(m) + '分' + parseInt(s) + '秒'
            }

            // 是否超过办理时限
            if (wflog.limitTime === null) {
                wflog.timeoutTimeLength = '未超时'
            } else {
                const limitTime = parseTime(wflog.limitTime)
                // 办理期限到完成时间的分钟数
                const timeLength = (endTime.getTime() - limitTime.getTime()) / (1000 * 60)

                if (timeLength <= 0) {
                    wflog.timeoutTimeLength = '未超时'
                } else {
                    const d = timeLength / (24 * 60)
                    const h = (timeLength % (24 * 60)) / 60
                    const m = (timeLength % (24 * 60)) % 60
                    const s = ((endTime.getTime() - startTime.getTime()) / 1000) % 60

                    if (d >= 1) {
                        wflog.timeoutTimeLength = parseInt(d) + '天' + parseInt(h) + '时' + parseInt(m) + '分'
                    } else if (h >= 1) {
                        wflog.timeoutTimeLength = parseInt(h) + '时' + parseInt(m) + '分'
                    } else {
                        wflog.timeoutTimeLength = parseInt(m) + '分' + parseInt(s) + '秒'
                    }
                    wflog.timeoutFlag = 1
                }
            }
        },
        rowClassName(rowInfo) {
            if (rowInfo.row.timeoutFlag === 1) {
                return 'todo-row timeout-row'
            } else {
                return 'todo-row'
            }
        },
        closeDialog() {
            this.dialogFormVisible = false
            this.fullscreen = false
            // this.showtechnological = false
            this.wfInstance = {}
            this.todoLogList = []
            this.toreadLogList = []
        },
        echartsClick(param) {
            this.tableList = []
            this.todoLogList.forEach((item) => {
                if (param.name === item.nodeName) {
                    this.tableList.push(item)
                }
            })
        },
        // 统计
        getXdata() {
            this.$http({
                method: 'POST',
                contentType: 'application/x-www-form-urlencoded',
                url: '/workflow/wfdProcessMgr/queryWfdNodeByProcessId',
                params: {
                    wfProcessId: this.wfInstance.wfId
                }
            }).then((res) => {
                if (res.code === 'success') {
                    this.xdata = []
                    const ids = []
                    const arr = res.body.listdata
                    arr.forEach((item) => {
                        if (item.nodeType === 1 && item.dccodeType === '' && item.name !== 'dfzjd' && item.name !== 'start' && item.name !== 'jsrw' && item.name !== 'jcjd' && item.name !== 'zyjd' && item.name !== 'jslc') {
                            this.xdata.push(item.name)
                            ids.push(item.id)
                        }
                    })
                    if (this.xdata.length > 10) {
                        this.xLabelRotate = 30
                    } else {
                        this.xLabelRotate = 0
                    }
                    this.ids = ids
                    const ydata1 = []
                    const ydata2 = []
                    const ydata3 = []
                    this.tableList = this.todoLogList
                    this.xdata.forEach((item) => { // x轴数据遍历
                        let num1 = 0// 已办
                        let num2 = 0// 未办未超时
                        let num3 = 0// 未办已超时
                        this.todoLogList.forEach((obj, j) => { // 总数据遍历
                            let todoTime = null // 办理期限
                            const nowdate = new Date().getTime()
                            if (obj.limitTime !== null && obj.limitTime !== '' && obj.limitTime !== undefined && obj.limitTime === '无时限') {
                                todoTime = nowdate
                            } else if (obj.limitTime !== null && obj.limitTime !== '' && obj.limitTime !== undefined) {
                                todoTime = new Date(obj.limitTime).getTime()
                            }
                            if (item === obj.nodeName && obj.completeTime && obj.completeTime !== '未完成') {
                                num1++
                            } else if (item === obj.nodeName && obj.completeTime && todoTime <= nowdate) {
                                num2++
                            } else if (item === obj.nodeName && obj.completeTime && todoTime >= nowdate) {
                                num3++
                            }
                        })
                        ydata1.push(num1)
                        ydata2.push(num2)
                        ydata3.push(num3)
                        this.allLabelNum.push(num1 + num2 + num3)
                    })

                    this.ydata = [ydata1, ydata2, ydata3]
                } else {
                    this.$message({
                        message: res.message,
                        type: 'warning'
                    })
                }
            }, (err) => {
                this.$message.error(err)
            })
        },
        labelFormatter(obj) {
            if (obj.seriesIndex === 2) {
                return this.allLabelNum[obj.dataIndex]
            } else {
                return ''
            }
        },
        // x轴格式化
        xLabelFormatter(val, index) {
            if (this.xdata.length <= 10) {
                let newval = ''
                const len = val.length
                for (let i = 0; i < len; i++) {
                    newval += val.substr(i, 1)
                    if ((i + 1) % 4 === 0)newval += '\r\n'
                }

                return newval
            } else {
                return val
            }
        },
        textDispose(val) {
            let nv = val.idea.replace(/\n/g, '<br>')
            if (nv.indexOf('{handwriting:1,') === 0) {
                nv = '<img name="handwritingidea" class="handwritingIdea" src="./apigw/workflow/wfInstanceNodelog/viewHandwritingIdea?wfNodelogId=' + val.id + '"></img>'
            }
            return nv
        },
        // 全屏设置
        setFullScreen() {
            this.echarts = false
            if (!this.fullscreen) {
                const dom = document.querySelectorAll('.el-tab-pane')
                const dialogBox = document.querySelectorAll('.wfNodeLoglist-dialog')[0]
                dialogBox.style.left = '0'
                dialogBox.style.top = '0'
                for (let i = 0; i < dom.length; i++) {
                    dom[i].classList.add('height100')
                }
            } else if (this.fullscreen) {
                const dom = document.querySelectorAll('.el-tab-pane')
                for (let i = 0; i < dom.length; i++) {
                    dom[i].classList.remove('height100')
                }
            }
            if (this.activeName === 'completeLog') {
                this.getXdata()
                this.$nextTick(() => {
                    this.echarts = true
                    this.fullscreen = !this.fullscreen
                    // $('.el-tab-pane').css('width', '100%')
                })
            } else {
                // const dom = document.getElementById('#pane-technological')
                // dom.classList.add('height100')el-tab-pane
                this.fullscreen = !this.fullscreen
            }

            var v = document.querySelector('.wfdialog-center-container')
            if (v) {
                v.style.width = '100%'
            }
        },
        clickloading() {
            this.loading = false
        },
        btnAddReaderClick($scope, toReadNodeName, dialogTitle, dialogType) {
            dialogType = dialogType || 'staff'
            // 代码模拟触发指令
            const el = {
                attrs: {
                    'multiple': 'true',
                    'dialog-title': dialogTitle || '添加阅文人',
                    'toReadNodeName': toReadNodeName || this.$vnode.context.curTN.passenger.toReadedNodeName
                },
                value: ''
            }
            $scope.onSelectStaffCompleted = this.onSelectStaffCompleted
            const vnode = {
                context: this,
                data: {
                    'attrs': { },
                    'model': { expression: '' }
                }
            }
            const binding = {
                value: dialogType
            }

            this.$bus.emit('openSelectDialog', el, binding, vnode)
        },
        onSelectStaffCompleted(selectedNodes, attr) {
            if (selectedNodes.length > 0) {
                const reqData = { fwWfInstance: JSON.stringify(this.$vnode.context.wfInstance) }
                reqData.openUrl = this.$vnode.context.submitHandle.openUrl
                reqData.nodeName = attr.toReadNodeName
                reqData.sender = this.$vnode.context.curTN.userName
                reqData.senderDept = this.$vnode.context.curTN.staffOrgName
                reqData.senderStaffId = this.$vnode.context.curTN.senderStaffId
                reqData.leaders = []

                selectedNodes.forEach(function(node) {
                    // 公司领导:潘健/panjian@402881033860d2d5013860d7e2b20004
                    reqData.leaders.push(node.orgFullName + ':' + node.name + '/' + node.account + '@' + node.id)
                })
                reqData.leaders = reqData.leaders.join(',')
                this.$bus.emit('showDoingDialog')

                this.$http({
                    method: 'POST',
                    contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                    data: qs.stringify(reqData),
                    url: 'workflow/wfInstance/createToReadItem'
                }).then((response) => {
                    this.$bus.emit('closeDoingDialog')

                    if (response.code === 'success') {
                        this.$message.success('已成功添加阅文人！')
                    } else {
                        this.$alert(response.message, '提示', { confirmButtonText: '确定', type: 'warning' })
                    }
                })
            }
        },
        btnReadedClick($scope) {
            this.$confirm('您是否确认已阅并关闭?', '确认操作', { type: 'warning' })
                .then(() => {
                    this.$bus.emit('showDoingDialog')
                    $scope.$wfEngine.saveWfInstance($scope, 'ManulReaded', $scope.wfParams).then(res => {
                        if (res.code === 'success') {
                            try {
                                const btnRefresh = window.opener.document.querySelector('.el-icon-refresh')
                                if (btnRefresh !== null) btnRefresh.parentElement.click()
                            } catch (e) {
                                console.log(e)
                            }
                            setTimeout(() => {
                                $scope.btnCloseClick()
                            }, 100)
                        } else {
                            this.$bus.emit('closeDoingDialog')
                            this.$alert(res.message, '提示', { type: 'warning' })
                        }
                    })
                })
        }
    }
}
</script>

<style scoped lang="scss">
/deep/ .todo-row {
    .cell{
        line-height: 18px;
    }

    td{
        padding:5px 0;
    }
}

/deep/ .timeout-row {
       .cell {
            color:red;
        }
    }

.el-tab-pane {
    height:550px;
    overflow-y: auto;
}

/deep/ .col-time .cell{
     word-break: break-word;
}
/deep/ .wfNodeLoglist-dialog{
    .el-scrollbar {
        width: 100%;
        height: 100%;
       .el-scrollbar__wrap {
            overflow-x: auto;
            height: calc(100% + 17px);
            padding-right: 20px;
            padding-bottom:40px;
        }
    }
    .el-dialog__body{
        padding-right: 0;
        padding-bottom: 0;

        .handwritingIdea{
            width: 100px;
        }
    }
    .el-tabs__nav-wrap::after{
        width: calc(100% - 20px);
    }

    .read-node-logs,
    .flow-node-logs{
        .el-scrollbar__view{ height: 100%; }
    }
}
.height100{
    height:calc(100vh - 120px);
}
/deep/ .el-dialog__headerbtn{
    top: 18px;
}
</style>
